import nprogress from 'nprogress'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import { asyncRoutes } from '@/router'
const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // determine whether the user has logged in
  const token = store.getters.token

  if (token) {
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      if (!store.getters.userId){
        // 1. 获取个人信息
        const res = await store.dispatch('user/getUserInfo')
  
        console.log(res.menus)
        const filterMenus = asyncRoutes.filter(it => res.menus.includes(it.children[0].name))
        filterMenus.push(// 404 page must be placed at the end !!!
        { path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterMenus)
        store.commit('menu/setMenuList', filterMenus)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if(whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
